package com.itmuch.box.service.sort;

import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.elasticsearch.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itmuch.box.core.base.BaseService;
import com.itmuch.box.dao.sort.SortRepository;
import com.itmuch.box.domain.sort.entity.Sort;
import com.itmuch.box.util.TreeUtil;

@Service
@Transactional
public class SortService extends BaseService<SortRepository, Sort> {
    @Autowired
    private TreeUtil<Sort> treeUtil;

    public List<Sort> findByCategoryId(int categoryId) {
        return this.dao.findByCategoryId(categoryId);
    }

    public Set<Sort> selectTopByCategoryId(Integer categoryId) {
        return this.dao.findByCategoryIdAndParentId(categoryId, 0);
    }

    public Set<Sort> selectChildrenById(Integer id) {
        return this.dao.findByParentId(id);
    }

    public Set<Integer> findChildrenWithSelfIdById(Integer id) {
        Set<Sort> children = this.selectChildrenById(id);
        Set<Integer> set = Sets.newHashSet();
        if (CollectionUtils.isNotEmpty(children)) {
            for (Sort item : children) {
                set.add(item.getId());
            }
        }
        set.add(id);
        return set;
    }

    public List<Sort> findByCategoryIdRecursion(Integer categoryId) {
        List<Sort> list = this.findByCategoryId(categoryId);
        List<Sort> list2 = this.treeUtil.genTree(list);
        return list2;
    }

}
